$(function () {
  function readData() {
    var list = localStorage.getItem("users");
    if (list !== null) {
      return JSON.parse(list);
    } else {
      return [];
    }
  }

  function savaData(data) {
    localStorage.setItem("users", data);
  }

  var users = readData();

  function checkRemember() {
    for (var i = 0; i < users.length; i++) {
      if (users[i].remember) {
        $("#loginname").val(users[i].username);
        $("#nloginpwd").val(users[i].password);
        $(".rem-click").prop("checked", users[i].remember);
        break;
      }
    }
  }

  function Pop(msg) {
    $(".pop p").html(msg);
    $(".pop").fadeIn();
    var time = 2;
    setInterval(() => {
      if (time == 0) {
        $(".pop").fadeOut();
      } else {
        time--;
      }
    }, 1000);
  }

  checkRemember();
  $(".confirm").click(function (event) {
    // var newData = { username: "", password: "", remember: false };
    var username = $("#loginname").val();
    var password = $("#nloginpwd").val();
    var checked = $(".rem-click").prop("checked");
    let find = false;

    if (username == "" || password == "") {
      Pop("错误，请补全信息！");
    } else {
      for (var i = 0; i < users.length; i++) {
        if (username == users[i].username || username == users[i].phone) {
          find = true;
          if (password == users[i].password) {
            localStorage.setItem("nowUser", users[i].username);
            users[i].remember = checked;
            savaData(JSON.stringify(users));
            document.location.href = "index.html";
          } else {
            Pop("错误，密码错误");
          }
        }
      }
      if (!find) {
        Pop("错误，用户名错误");
      }
    }
  });
});
